//
//  PostViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 5/30/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "PostViewController.h"
#import "API.h"
#import "DatabaseManager.h"
#import <QuartzCore/QuartzCore.h>

@implementation PostViewController

@synthesize post;
@synthesize postType;
@synthesize imageViewThumbnail;
@synthesize labelTitle;
@synthesize textViewContent;
@synthesize webViewContent;
@synthesize bizFax,bizZip,bizCity,bizEmail,bizPhone,bizState,bizAddress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [post release];
    [imageViewThumbnail release];
    [labelTitle release];
    [textViewContent release];
    [webViewContent release];
    [bizAddress release];
    [bizCity release];
    [bizEmail release];
    [bizState release];
    [bizPhone release];
    [bizZip release];
    [bizFax release];
    [super dealloc];
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

- (void)viewDidLoad
{
    [super viewDidLoad];
    //[self.tableView setBounces:NO];
    [self.tableView setPagingEnabled:YES];
    [self.tableView setShowsVerticalScrollIndicator:YES];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    self.title = @"Business Profile";
        
//    labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 224, 280, 36)];
//    [labelTitle setTextAlignment:UITextAlignmentLeft];
//    [self.view addSubview:labelTitle];
//    textViewContent = [[UITextView alloc] initWithFrame:CGRectMake(20, 260, 280, 102)];
//    [textViewContent setEditable:NO];
//    [self.view addSubview:textViewContent];

        
    if (postType == REMOTE_POST) {
        UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [waitingIndicator setTag:1000];
        [waitingIndicator setCenter:CGPointMake(160, 181)];
        [self.view addSubview:waitingIndicator];
        [waitingIndicator startAnimating];
        [waitingIndicator release];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPostReceived:) name:kPostReceivedNotification object:nil];
        API *api = [API sharedInstance];
        [api getPostWithId:post.postId];
    }
    else {
        //labelTitle.text = post.title;
        //textViewContent.text = post.content;
        [self performSelector:@selector(loadThumbnail) withObject:nil afterDelay:0.05];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    tableView.separatorColor =  [UIColor clearColor];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    int section = indexPath.section;
    NSLog(@"section = %d, row = %d", section, indexPath.row);
    //if (section == 0 && indexPath.row==0) {
        //cell.textLabel.text = post.description;
        imageViewThumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 210)];
        [imageViewThumbnail.layer setBorderWidth:1.0f];
        [imageViewThumbnail.layer setBorderColor:[UIColor blackColor].CGColor];
        [imageViewThumbnail.layer setCornerRadius:3.0f];
        [imageViewThumbnail setContentMode:UIViewContentModeScaleAspectFit];
        [cell addSubview:imageViewThumbnail];
        //[cell.contentView sizeToFit];
   
        //cell.textLabel.text = post.phone;
        webViewContent = [[UIWebView alloc] initWithFrame:CGRectMake(10, 220, 300, 102)];
        [cell addSubview:webViewContent];
  
        //cell.textLabel.text = post.phone;
        
        // UILabel *contactInfo = [[UILabel alloc] initWithFrame:CGRectMake(10, 340, 280, 30)];
        UIButton *contactInfo = [[UIButton alloc] initWithFrame:CGRectMake(10, 340, 80, 40)];
       
        [contactInfo setTitle:@"Contact info" forState:UIControlStateNormal];
        [contactInfo addTarget:self action:@selector(onContactInfoClicked:) forControlEvents:UIControlEventTouchUpInside];
//        contactInfo.text = @"Contact info:";
//        [contactInfo setFont:[UIFont fontWithName:@"Helvetica" size:14]];
        [cell addSubview:contactInfo];
        [contactInfo release];


  

    //}
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.contentView sizeToFit];
    tableView.rowHeight = 440;
    
//    if( section == 1 ){
//        tableView.rowHeight = 220;
//    } else {
//        tableView.rowHeight = 35;
//    }

    return cell;
}

-(void) onContactInfoClicked:(id)sender
{
    UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 400)];
    
    if( bizPhone == nil)
        bizPhone = [[UILabel alloc] initWithFrame:CGRectMake(10, 370, 280, 30)];
    [bizPhone setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizPhone];
    
    if( bizEmail == nil)
        bizEmail = [[UILabel alloc] initWithFrame:CGRectMake(10, 400, 280, 30)];
    [bizEmail setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizEmail];
    
    if( bizFax == nil)
        bizFax = [[UILabel alloc] initWithFrame:CGRectMake(10, 530, 280, 30)];
    [bizFax setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizFax];
    
    if( bizAddress == nil)
        bizAddress = [[UILabel alloc] initWithFrame:CGRectMake(10, 560, 280, 30)];
    [bizAddress setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizAddress];
    
    if( bizCity == nil)
        bizCity = [[UILabel alloc] initWithFrame:CGRectMake(10, 590, 280, 30)];
    [bizCity setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizCity];
    
    if( bizZip == nil)
        bizZip = [[UILabel alloc] initWithFrame:CGRectMake(10, 620, 280, 30)];
    [bizZip setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizZip];
    
    if( bizState == nil)
        bizState = [[UILabel alloc] initWithFrame:CGRectMake(10, 650, 280, 30)];
    [bizState setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [cell addSubview:bizState];
    
    [self.view addSubview:cell];
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Post received notification

- (void)onPostReceived:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kPostReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    NSDictionary *result = [notification userInfo];
    NSDictionary *bizInfo = [result objectForKey:@"business_info"];
//    NSString *title = [[result objectForKey:@"post"] objectForKey:@"title"];
//    NSString *content = [[result objectForKey:@"post"] objectForKey:@"content"];
//    NSString *thumbnail = [[result objectForKey:@"post"] objectForKey:@"image"];
    //NSString *title = [[result objectForKey:@"business_info"] objectForKey:@"title"];
    NSString *content = [bizInfo objectForKey:@"description"];
    NSString *thumbnail = [bizInfo objectForKey:@"display_image"];
    //post.title = title;
    post.content = content;
    
    bizPhone.text = [@"Phone:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"phone"]];
    bizEmail.text = [@"Email:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"email"]];
    bizFax.text = [@"Fax:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"fax"]];
    bizAddress.text = [@"Address:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"business_address"]];
    bizCity.text = [@"City:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"city"]];
    bizZip.text = [@"Zip:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"zip"]];
    bizState.text = [@"State:" stringByAppendingFormat:@"%@", [bizInfo objectForKey:@"state"]];
    
    [webViewContent loadHTMLString:content baseURL:nil];
//    labelTitle.text = post.title;
//    textViewContent.text = post.content;
    
    
    if (thumbnail != nil && ![thumbnail isEqual:[NSNull null]]) {
        post.thumbnail = thumbnail;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbnail]];
        imageViewThumbnail.image = [UIImage imageWithData:data];
    }
    
    DatabaseManager *databaseManager = [DatabaseManager sharedInstance];
    if (![databaseManager isPostExisted:post.postId]) {
        NSLog(@"Go here");
        UIButton *buttonAddToFavourite = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [buttonAddToFavourite setFrame:CGRectMake(150, 330, 150, 30)];
        [buttonAddToFavourite setTitle:@"Add to Favourite" forState:UIControlStateNormal];
        [buttonAddToFavourite addTarget:self action:@selector(onButtonAddToFavouriteClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:buttonAddToFavourite];
        //[buttonAddToFavourite setEnabled:NO];
    }
    
//[self.tableView reloadData];
}

#pragma mark - Thumbnail loading

- (void)loadThumbnail
{
    if (post.thumbnail != nil && ![post.thumbnail isEqual:[NSNull null]]) {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:post.thumbnail]];
        imageViewThumbnail.image = [UIImage imageWithData:data];
    }
}

#pragma mark - Button click handlers

- (void)onButtonAddToFavouriteClicked:(id)sender
{
    DatabaseManager *databaseManager = [DatabaseManager sharedInstance];
    [databaseManager addPost:post];
    UIButton *buttonAddToFavourite = (UIButton *)sender;
    [buttonAddToFavourite setEnabled:NO];
    
    //buttonAddToFavourite.alpha = 0.0;
    //buttonAddToFavourite.opaque = YES;
    [buttonAddToFavourite removeFromSuperview];
    

    
    [[NSNotificationCenter defaultCenter] postNotificationName:kPostAddedToFavouritesNotification object:nil userInfo:[NSDictionary dictionaryWithObject:post forKey:@"new post"]];
}

@end
